<?php

/**
 *   OPENSHOP 管理中心公用文件
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: init.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

if (!defined('IN_OS')){
    die('Access Denied');
}

/**
 * 取得推荐类型列表
 * @return  array   推荐类型列表
 */
function get_intro_list()
{
    return array(
        'is_best'    => $GLOBALS['_LANG']['is_best'],
        'is_new'     => $GLOBALS['_LANG']['is_new'],
        'is_hot'     => $GLOBALS['_LANG']['is_hot'],
        'is_promote' => $GLOBALS['_LANG']['is_promote'],
        'all_type' => $GLOBALS['_LANG']['all_type'],
    );
}

/**
 * 取得重量单位列表
 * @return  array   重量单位列表
 */
function get_unit_list()
{
    return array(
        '1'     => $GLOBALS['_LANG']['unit_kg'],
        '0.001' => $GLOBALS['_LANG']['unit_g'],
    );
}

/**
 * 取得客户等级列表
 * @return  array   客户等级列表
 */
function get_user_rank_list()
{
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('user_rank') .
           " ORDER BY min_points";

    return $GLOBALS['db']->getAll($sql);
}

/**
 * 取得某商品的客户价格列表
 * @param   int     $goods_id   商品编号
 * @return  array   客户价格列表 user_rank => user_price
 */
function get_member_price_list($goods_id)
{
    /* 取得客户价格 */
    $price_list = array();
    $sql = "SELECT user_rank, user_price FROM " .
           $GLOBALS['os']->table('member_price') .
           " WHERE goods_id = '$goods_id'";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $price_list[$row['user_rank']] = $row['user_price'];
    }

    return $price_list;
}

/**
 * 插入或更新商品属性
 * @param   int     $goods_id       商品编号
 * @param   array   $id_list        属性编号数组
 * @param   array   $is_spec_list   是否规格数组 'true' | 'false'
 * @param   array   $value_price_list   属性值数组
 */
function handle_goods_attr($goods_id, $id_list, $is_spec_list, $value_price_list)
{
    /* 循环处理每个属性 */
    foreach ($id_list AS $key => $id)
    {
        $is_spec = $is_spec_list[$key];
        if ($is_spec == 'false')
        {
            $value = $value_price_list[$key];
            $price = '';
        }
        else
        {
            $value_list = array();
            $price_list = array();
            if ($value_price_list[$key])
            {
                $vp_list = explode(chr(13), $value_price_list[$key]);
                foreach ($vp_list AS $v_p)
                {
                    $arr = explode(chr(9), $v_p);
                    $value_list[] = $arr[0];
                    $price_list[] = $arr[1];
                }
            }
            $value = join(chr(13), $value_list);
            $price = join(chr(13), $price_list);
        }

        // 插入或更新记录
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('goods_attr') . " WHERE goods_id = '$goods_id' AND attr_id = '$id'";
        if ($GLOBALS['db']->getOne($sql) > 0)
        {
            $sql = "UPDATE " . $GLOBALS['os']->table('goods_attr') . " SET " .
                    "attr_value = '$value', " .
                    "attr_price = '$price' " .
                    "WHERE goods_id = '$goods_id' " .
                    "AND attr_id = '$id' LIMIT 1";
        }
        else
        {
            $sql = "INSERT INTO " . $GLOBALS['os']->table('goods_attr') . " (goods_id, attr_id, attr_value, attr_price) " .
                    "VALUES ('$goods_id', '$id', '$value', '$price')";
        }
        $GLOBALS['db']->query($sql);
    }
}

/**
 * 保存某商品的客户价格
 * @param   int     $goods_id   商品编号
 * @param   array   $rank_list  等级列表
 * @param   array   $price_list 价格列表
 * @return  void
 */
function handle_member_price($goods_id, $rank_list, $price_list)
{
    /* 循环处理每个客户等级 */
    foreach ($rank_list AS $key => $rank)
    {
        /* 客户等级对应的价格 */
        $price = $price_list[$key];

        // 插入或更新记录
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('member_price') .
               " WHERE goods_id = '$goods_id' AND user_rank = '$rank'";
        if ($GLOBALS['db']->getOne($sql) > 0)
        {
            /* 如果客户价格是小于0则删除原来价格，不是则更新为新的价格 */
            if ($price < 0)
            {
                $sql = "DELETE FROM " . $GLOBALS['os']->table('member_price') .
                       " WHERE goods_id = '$goods_id' AND user_rank = '$rank' LIMIT 1";
            }
            else
            {
                $sql = "UPDATE " . $GLOBALS['os']->table('member_price') .
                       " SET user_price = '$price' " .
                       "WHERE goods_id = '$goods_id' " .
                       "AND user_rank = '$rank' LIMIT 1";
            }
        }
        else
        {
            if ($price == -1)
            {
                $sql = '';
            }
            else
            {
                $sql = "INSERT INTO " . $GLOBALS['os']->table('member_price') . " (goods_id, user_rank, user_price) " .
                       "VALUES ('$goods_id', '$rank', '$price')";
            }
        }

        if ($sql)
        {
            $GLOBALS['db']->query($sql);
        }
    }
}

/**
 * 保存某商品的扩展分类
 * @param   int     $goods_id   商品编号
 * @param   array   $cat_list   分类编号数组
 * @return  void
 */
function handle_other_cat($goods_id, $cat_list)
{
    /* 查询现有的扩展分类 */
    $sql = "SELECT cat_id FROM " . $GLOBALS['os']->table('goods_cat') .
            " WHERE goods_id = '$goods_id'";
    $exist_list = $GLOBALS['db']->getCol($sql);

    /* 删除不再有的分类 */
    $delete_list = array_diff($exist_list, $cat_list);
    if ($delete_list)
    {
        $sql = "DELETE FROM " . $GLOBALS['os']->table('goods_cat') .
                " WHERE goods_id = '$goods_id' " .
                "AND cat_id " . db_create_in($delete_list);
        $GLOBALS['db']->query($sql);
    }

    /* 添加新加的分类 */
    $add_list = array_diff($cat_list, $exist_list, array(0));
    foreach ($add_list AS $cat_id)
    {
        // 插入记录
        $sql = "INSERT INTO " . $GLOBALS['os']->table('goods_cat') .
                " (goods_id, cat_id) " .
                "VALUES ('$goods_id', '$cat_id')";
        $GLOBALS['db']->query($sql);
    }
}

/**
 * 保存某商品的关联商品
 * @param   int     $goods_id
 * @return  void
 */
function handle_link_goods($goods_id)
{
    $sql = "UPDATE " . $GLOBALS['os']->table('link_goods') . " SET " .
            " goods_id = '$goods_id' " .
            " WHERE goods_id = '0'" .
            " AND admin_id = '$_SESSION[admin_id]'";
    $GLOBALS['db']->query($sql);

    $sql = "UPDATE " . $GLOBALS['os']->table('link_goods') . " SET " .
            " link_goods_id = '$goods_id' " .
            " WHERE link_goods_id = '0'" .
            " AND admin_id = '$_SESSION[admin_id]'";
    $GLOBALS['db']->query($sql);
}

/**
 * 保存某商品的配件
 * @param   int     $goods_id
 * @return  void
 */
function handle_group_goods($goods_id)
{
    $sql = "UPDATE " . $GLOBALS['os']->table('group_goods') . " SET " .
            " parent_id = '$goods_id' " .
            " WHERE parent_id = '0'" .
            " AND admin_id = '$_SESSION[admin_id]'";
    $GLOBALS['db']->query($sql);
}

/**
 * 保存某商品的关联文章
 * @param   int     $goods_id
 * @return  void
 */
function handle_goods_article($goods_id)
{
    $sql = "UPDATE " . $GLOBALS['os']->table('goods_article') . " SET " .
            " goods_id = '$goods_id' " .
            " WHERE goods_id = '0'" .
            " AND admin_id = '$_SESSION[admin_id]'";
    $GLOBALS['db']->query($sql);
}

/**
 * 保存某商品的相册图片
 * @param   int     $goods_id
 * @param   array   $image_files
 * @param   array   $image_descs
 * @return  void
 */
function handle_gallery_image($goods_id, $image_files, $image_descs)
{
    /* 是否处理缩略图 */
    $proc_thumb = (isset($GLOBALS['shop_id']) && $GLOBALS['shop_id'] > 0)? false : true;
    foreach ($image_descs AS $key => $img_desc)
    {
        /* 是否成功上传 */
        $flag = false;
        if (isset($image_files['error']))
        {
            if ($image_files['error'][$key] == 0)
            {
                $flag = true;
            }
        }
        else
        {
            if ($image_files['tmp_name'][$key] != 'none')
            {
                $flag = true;
            }
        }

        if ($flag)
        {
            $upload = array(
                'name' => $image_files['name'][$key],
                'type' => $image_files['type'][$key],
                'tmp_name' => $image_files['tmp_name'][$key],
                'size' => $image_files['size'][$key],
            );
            if (isset($image_files['error']))
            {
                $upload['error'] = $image_files['error'][$key];
            }

		    if($GLOBALS['filesync']->sync_type=='ftp'){
	            $GLOBALS['filesync']->connect();
	            $GLOBALS['filesync']->setting('goods_gallery');
		        $gallery_affix_data   = $GLOBALS['filesync']->put_up($upload); // 原始图片
	            $img_original   = $gallery_affix_data['virtual_path'];
	            $GLOBALS['filesync']->quit();
		    }else{
            	$img_original = $GLOBALS['filesync']->upload_image($upload);		    	
		    }            

            if ($img_original === false || empty($img_original))
            {
                sys_msg('相册上传错误', 1, array(), false);
            }
	         	        
            
            $img_url = $img_original;           

            $thumb_url = $img_original;       
            
            /* 重新格式化图片名称 */
            $img_original = reformat_image_name('gallery', $goods_id, $img_original);
            if($img_original!==false){
            	$img_url = $img_original;        
            	$thumb_url = $img_original;             	
            }
            $sql = "INSERT INTO " . $GLOBALS['os']->table('goods_gallery') . " (goods_id, img_url, img_desc, thumb_url, img_original, color_id, type, sort_order) " .
                   "VALUES ('$goods_id', '$img_url', '$img_desc', '$thumb_url', '$img_original', ".$_POST['img_color_id'][$key].", ".$_POST['img_type'][$key].", ".$_POST['img_sort_order'][$key].")";            
            $GLOBALS['db']->query($sql);
        }
    }
}

/**
 * 修改商品某字段值
 * @param   string  $goods_id   商品编号，可以为多个，用 ',' 隔开
 * @param   string  $field      字段名
 * @param   string  $value      字段值
 * @return  bool
 */
function update_goods($goods_id, $field, $value)
{
    if ($goods_id)
    {
        /* 清除缓存 */
        clear_cache_files();

        $sql = "UPDATE " . $GLOBALS['os']->table('goods') .
                " SET $field = '$value' , last_update = '". gmtime() ."' " .
                "WHERE goods_id " . db_create_in($goods_id);

        return $GLOBALS['db']->query($sql);
    }
    else
    {
        return false;
    }
}

/**
 * 从回收站删除多个商品
 * @param   mix     $goods_id   商品id列表：可以逗号格开，也可以是数组
 * @return  void
 */
function delete_goods($goods_id)
{
    if (empty($goods_id))
    {
        return;
    }

    /* 取得有效商品id */
    $sql = "SELECT DISTINCT goods_id FROM " . $GLOBALS['os']->table('goods') .
            " WHERE goods_id " . db_create_in($goods_id) . " AND is_delete = 1";
    $goods_id = $GLOBALS['db']->getCol($sql);
    if (empty($goods_id))
    {
        return;
    }

    /* 删除商品图片和轮播图片文件 */
    $sql = "SELECT goods_id FROM " . $GLOBALS['os']->table('goods') .
            " WHERE goods_id " . db_create_in($goods_id);
    $res = $GLOBALS['db']->query($sql);
    while ($goods = $GLOBALS['db']->fetchRow($res))
    {
        if ($goods['goods_id'] && $goods['goods_id']>0)
        {
		    $GLOBALS['filesync']->connect();
		    @$GLOBALS['filesync']->drop($goods['goods_id'], 'goods');
		    $GLOBALS['filesync']->quit();
        }
    }

    /* 删除商品 */
    $sql = "DELETE FROM " . $GLOBALS['os']->table('goods') .
            " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);

    /* 删除商品相册的图片文件 */
    $sql = "SELECT img_id FROM " . $GLOBALS['os']->table('goods_gallery') .
            " WHERE goods_id " . db_create_in($goods_id);
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
    	if($row['img_id'] && $row['img_id']>0){
		    $GLOBALS['filesync']->connect();
		    @$GLOBALS['filesync']->drop($row['img_id'], 'goods_gallery');
		    $GLOBALS['filesync']->quit();
    	}
    }

    /* 删除商品相册 */
    $sql = "DELETE FROM " . $GLOBALS['os']->table('goods_gallery') . " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);

    /* 删除相关表记录 */
    $sql = "DELETE FROM " . $GLOBALS['os']->table('collect_goods') . " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('goods_article') . " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('goods_attr') . " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('goods_cat') . " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('member_price') . " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('group_goods') . " WHERE parent_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('group_goods') . " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('link_goods') . " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('link_goods') . " WHERE link_goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('tag') . " WHERE goods_id " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    $sql = "DELETE FROM " . $GLOBALS['os']->table('comment') . " WHERE comment_type = 0 AND id_value " . db_create_in($goods_id);
    $GLOBALS['db']->query($sql);
    
    // 删除相关库存表记录
    $sql = "DELETE FROM " . $GLOBALS['os']->table('goods_inventory') . " WHERE goods_id " . db_create_in($goods_id);
	$GLOBALS['db']->query($sql);
	// END 添加
    
    /* 删除相应虚拟商品记录 */
    $sql = "DELETE FROM " . $GLOBALS['os']->table('virtual_card') . " WHERE goods_id " . db_create_in($goods_id);
    if (!$GLOBALS['db']->query($sql, 'SILENT') && $GLOBALS['db']->errno() != 1146)
    {
        die($GLOBALS['db']->error());
    }

    /* 清除缓存 */
    clear_cache_files();
}

/**
 * 为某商品生成唯一的货号
 * @param   int     $goods_id   商品编号
 * @return  string  唯一的货号
 */
function generate_goods_sn($goods_id)
{
    $goods_sn = $GLOBALS['_CFG']['sn_prefix'] . str_repeat('0', 6 - strlen($goods_id)) . $goods_id;

    $sql = "SELECT goods_sn FROM " . $GLOBALS['os']->table('goods') .
            " WHERE goods_sn LIKE '" . mysql_like_quote($goods_sn) . "%' AND goods_id <> '$goods_id' " .
            " ORDER BY LENGTH(goods_sn) DESC";
    $sn_list = $GLOBALS['db']->getCol($sql);
    if (in_array($goods_sn, $sn_list))
    {
        $max = pow(10, strlen($sn_list[0]) - strlen($goods_sn) + 1) - 1;
        $new_sn = $goods_sn . mt_rand(0, $max);
        while (in_array($new_sn, $sn_list))
        {
            $new_sn = $goods_sn . mt_rand(0, $max);
        }
        $goods_sn = $new_sn;
    }

    return $goods_sn;
}

/**
 * 取得通用属性和某分类的属性，以及某商品的属性值
 * @param   int     $cat_id     分类编号
 * @param   int     $goods_id   商品编号
 * @return  array   规格与属性列表
 */
function get_attr_list($cat_id, $goods_id = 0)
{
    if (empty($cat_id) || $cat_id<=0)
    {
         return false;
    }

    // 查询属性值及商品的属性值
    $sql = "SELECT a.attr_id, a.attr_name, a.attr_input_type, a.attr_type, a.attr_values, v.attr_value, v.attr_price ".
            "FROM " .$GLOBALS['os']->table('attribute'). " AS a ".
            "LEFT JOIN " .$GLOBALS['os']->table('goods_attr'). " AS v ".
            "ON v.attr_id = a.attr_id AND v.goods_id = '$goods_id' ".
            "WHERE a.cat_id = " . intval($cat_id) ." OR a.cat_id = 0 ".
            "ORDER BY a.sort_order, a.attr_type, a.attr_id, v.attr_price, v.goods_attr_id";

    $row = $GLOBALS['db']->GetAll($sql);

    return $row;
}

/**
 * 根据属性数组创建属性的表单
 *
 * @access  public
 * @param   int     $cat_id     分类编号
 * @param   int     $goods_id   商品编号
 * @return  string
 */
function build_attr_html($cat_id, $goods_id = 0)
{
    $attr = get_attr_list($cat_id, $goods_id);
    $html = '<table width="100%" id="attrTable">';
    $spec = 0;

    if(is_array($attr) && sizeof($attr)>0){
	    foreach ($attr AS $key => $val)
	    {
	        $html .= "<tr><td class='label'>";
	        if ($val['attr_type'] == 1 || $val['attr_type'] == 2)
	        {
	            $html .= ($spec != $val['attr_id']) ?
	                "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" :
	                "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
	            $spec = $val['attr_id'];
	        };
	
	        $html .= "$val[attr_name]</td><td><input type='hidden' name='attr_id_list[]' value='$val[attr_id]' />";
	
	        if ($val['attr_input_type'] == 0)
	        {
	            $html .= '<input name="attr_value_list[]" type="text" value="' .htmlspecialchars($val['attr_value']). '" size="40" /> ';
	        }
	        elseif ($val['attr_input_type'] == 2)
	        {
	            $html .= '<textarea name="attr_value_list[]" rows="3" cols="40">' .htmlspecialchars($val['attr_value']). '</textarea>';
	        }
	        else{
	            $html .= '<select name="attr_value_list[]">';
	            $html .= '<option value="">' .$GLOBALS['_LANG']['select_please']. '</option>';
	
	            $attr_values = explode("\n", $val['attr_values']);
	
	            foreach ($attr_values AS $opt)
	            {
	                $opt    = trim(htmlspecialchars($opt));
	
	                $html   .= ($val['attr_value'] != $opt) ?
	                    '<option value="' . $opt . '">' . $opt . '</option>' :
	                    '<option value="' . $opt . '" selected="selected">' . $opt . '</option>';
	            }
	            $html .= '</select> ';
	        }
	
	        $html .= ($val['attr_type'] == 1 || $val['attr_type'] == 2) ?
	            $GLOBALS['_LANG']['spec_price'].' <input type="text" name="attr_price_list[]" value="' . $val['attr_price'] . '" size="5" maxlength="10" />' :
	            ' <input type="hidden" name="attr_price_list[]" value="0" />';
	
	        $html .= '</td></tr>';
	    }
    }else{
    	$html .= "<tr><td class='label'>";
    	$html .= "<div style='color:red; text-align:center; padding:15px; border:#ccd5d2 1px solid;'>该商品分类没关联类型</div>";
    	$html .= '</td></tr>';
    }
    $html .= '</table>';

    return $html;
}

/**
 * 获得指定商品相关的商品
 *
 * @access  public
 * @param   integer $goods_id
 * @return  array
 */
function get_linked_goods($goods_id)
{
    $sql = "SELECT lg.link_goods_id AS goods_id, g.goods_name, lg.is_double " .
            "FROM " . $GLOBALS['os']->table('link_goods') . " AS lg, " .
                $GLOBALS['os']->table('goods') . " AS g " .
            "WHERE lg.goods_id = '$goods_id' " .
            "AND lg.link_goods_id = g.goods_id ";
    if ($goods_id == 0)
    {
        $sql .= " AND lg.admin_id = '$_SESSION[admin_id]'";
    }
    $row = $GLOBALS['db']->getAll($sql);

    foreach ($row AS $key => $val)
    {
        $linked_type = $val['is_double'] == 0 ? $GLOBALS['_LANG']['single'] : $GLOBALS['_LANG']['double'];

        $row[$key]['goods_name'] = $val['goods_name'] . " -- [$linked_type]";

        unset($row[$key]['is_double']);
    }

    return $row;
}

/**
 * 获得指定商品的配件
 *
 * @access  public
 * @param   integer $goods_id
 * @return  array
 */
function get_group_goods($goods_id)
{
    $sql = "SELECT gg.goods_id, CONCAT(g.goods_name, ' -- [', gg.goods_price, ']') AS goods_name " .
            "FROM " . $GLOBALS['os']->table('group_goods') . " AS gg, " .
                $GLOBALS['os']->table('goods') . " AS g " .
            "WHERE gg.parent_id = '$goods_id' " .
            "AND gg.goods_id = g.goods_id ";
    if ($goods_id == 0)
    {
        $sql .= " AND gg.admin_id = '$_SESSION[admin_id]'";
    }
    $row = $GLOBALS['db']->getAll($sql);

    return $row;
}

/**
 * 获得商品的关联文章
 *
 * @access  public
 * @param   integer $goods_id
 * @return  array
 */
function get_goods_articles($goods_id)
{
    $sql = "SELECT g.article_id, a.title " .
            "FROM " .$GLOBALS['os']->table('goods_article') . " AS g, " .
                $GLOBALS['os']->table('article') . " AS a " .
            "WHERE g.goods_id = '$goods_id' " .
            "AND g.article_id = a.article_id ";
    if ($goods_id == 0)
    {
        $sql .= " AND g.admin_id = '$_SESSION[admin_id]'";
    }
    $row = $GLOBALS['db']->getAll($sql);

    return $row;
}

/**
 * 获得商品列表
 *
 * @access  public
 * @params  integer $isdelete
 * @params  integer $real_goods
 * @return  array
 */
function goods_list($is_delete, $real_goods=1){
	
    /* 过滤条件 */
    $param_str = '-' . $is_delete . '-' . $real_goods;
    $result = get_filter($param_str);
    if ($result === false)
    {
        $day = getdate();
        $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

        $filter['cat_id']           = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        $filter['intro_type']       = empty($_REQUEST['intro_type']) ? '' : trim($_REQUEST['intro_type']);
        $filter['is_promote']       = empty($_REQUEST['is_promote']) ? 0 : intval($_REQUEST['is_promote']);
        $filter['stock_warning']    = empty($_REQUEST['stock_warning']) ? 0 : intval($_REQUEST['stock_warning']);
        $filter['brand_id']         = empty($_REQUEST['brand_id']) ? 0 : intval($_REQUEST['brand_id']);
		$filter['updown_id']        = empty($_REQUEST['updown_id']) ? 0 : intval($_REQUEST['updown_id']);
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'goods_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['extension_code']   = empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);
        $filter['is_delete']        = $is_delete;
        $filter['real_goods']       = $real_goods;

        $where = $filter['cat_id'] > 0 ? " AND " . get_children($filter['cat_id']) : '';

        /* 推荐类型 */
        switch ($filter['intro_type'])
        {
            case 'is_best':
                $where .= " AND is_best=1";
                break;
            case 'is_hot':
                $where .= ' AND is_hot=1';
                break;
            case 'is_new':
                $where .= ' AND is_new=1';
                break;
            case 'is_presale':
                $where .= ' AND is_presale=1';
                break;
            case 'is_promote':
                $where .= " AND is_promote = 1 AND promote_price > 0 AND promote_start_date <= '$today' AND promote_end_date >= '$today'";
                break;
            case 'all_type';
                $where .= " AND (is_best=1 OR is_hot=1 OR is_new=1 OR is_presale=1 OR (is_promote = 1 AND promote_price > 0 AND promote_start_date <= '" . $today . "' AND promote_end_date >= '" . $today . "'))";
        }

        /* 库存警告 */
        if ($filter['stock_warning'])
        {
            $where .= ' AND goods_number <= warn_number ';
        }

        /* 品牌 */
        if ($filter['brand_id'])
        {
            $where .= " AND brand_id='$filter[brand_id]'";
        }

        /* 扩展 */
        if ($filter['extension_code'])
        {
            $where .= " AND extension_code='$filter[extension_code]'";
        } 
        /*上下架*/
		if ($filter['updown_id'])
		{
			$updown=$filter[updown_id]-1;
			$where .= " AND is_on_sale='$updown'";
		} 
        /* 关键字 */
        if (!empty($filter['keyword']))
        { 
			$filter['keyword']=urldecode( $filter['keyword']  )  ;
            $where .= " AND (goods_sn LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }

        if ($real_goods > -1)
        {
            $where .= " AND is_real='$real_goods'";
        }

        /* 记录总数 */
        $sql = "SELECT COUNT(*) FROM " .$GLOBALS['os']->table('goods'). " AS g WHERE is_delete='$is_delete' $where";
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */
        $filter = page_and_size($filter);

        /**
         * 添加对商品库位的查询
         */

        $sql = "SELECT goods_id, goods_name, goods_sn, shop_price, is_on_sale, is_best, is_new, is_hot, is_presale, depot_id, seat_id, shipping_days, statistic_days, hot_number, sort_order, goods_number, storage_location,integral, (promote_price > 0 AND promote_start_date <= '$today' AND promote_end_date >= '$today') AS is_promote 
				,(select SUM(goods_number_actual) FROM open_goods_inventory as gi where g.goods_id =gi.goods_id) as goods_number_actual
				,(select SUM(goods_number_available) FROM open_goods_inventory as gi where g.goods_id =gi.goods_id) as goods_number_available,tb_i.iid  ".
        	    " FROM " . $GLOBALS['os']->table('goods') . " AS g 
        	    left join open_tb_item as tb_i on tb_i.outer_id = g.goods_sn 
        	    WHERE is_delete='$is_delete' $where" .
                " ORDER BY $filter[sort_by] $filter[sort_order] ".
                " LIMIT " . $filter['start'] . ",$filter[page_size]";         
        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql, $param_str);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
//    make_json_error($sql);
//    die($sql);
//    exit;
    $row = $GLOBALS['db']->getAll($sql);
    foreach($row as $key => $val) {
    	$row[$key]['statistic_days'] = intval($val['statistic_days']);
    	$row[$key]['hot_number'] = intval($val['hot_number']);
    }

    return array('goods' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

/**
 * 批量更新商品承诺发货天数
 *
 * @access  public
 * @params  array $goods_ids
 * @return  true
 */
function update_goods_shipping_days($goods_ids=array(), $goods_sns=array()) {
	if (count($goods_ids) > 0 || count($goods_sns) > 0) {
		if (count($goods_ids) > 0) {
			foreach($goods_ids as $key => $val) {
				update_good_shipping_days($val);
			}
		} else {
			foreach($goods_sns as $key => $val) {
				update_good_shipping_days(0, $val);
			}
		}
	} else {
		$goods_ids = $GLOBALS['db']->getCol("SELECT goods_id FROM " . $GLOBALS['os']->table('goods'));
		foreach($goods_ids as $key => $val) {
			update_good_shipping_days($val);
		}
	}
	
	return true;
}

/**
 * 更新单个商品承诺发货天数
 *
 * @access  public
 * @params  int		$goods_id
 * @params	string	$goods_sn
 * @return  true
 */
function update_good_shipping_days($goods_id=0, $goods_sn='') {
	if (!$goods_id && !$goods_sn) {
		return false;
	} else {
		$keys = array();
		$search = '';
		$field_str = $goods_id ? "goods_id='{$goods_id}'" : "goods_sn='{$goods_sn}'";
		$row = $GLOBALS['db']->getRow("SELECT 1 AS is_general,is_best,is_new,is_hot,is_presale FROM " . $GLOBALS['os']->table('goods') . " WHERE $field_str ");
		$keys = array_keys($row);
		for($i=0;$i<count($keys);$i++) { if ($row[$keys[$i]]) { $search .= "'" . $keys[$i] . "',"; } }
		$search = preg_replace("/,$/", '', $search);
		$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('goods') . " SET shipping_days = ( SELECT MAX(shipping_days) FROM " . $GLOBALS['os']->table('promise_delivery') . " WHERE recommend_type IN ( $search ) ) WHERE $field_str ");
	}
	
	return true;
}

/**
 * XX天，日均销售数量达到YY的商品，自动定义为热销款
 *
 * @access  public
 * @params  integer $clear
 * @return  true
 */
function auto_set_hot($clear=0) {
	if ($clear) { //清除历史热销款
		$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('goods') . " SET is_hot='0' WHERE is_hot='1' AND statistic_days>'0' AND hot_number>'0'");
	}
	//当前GMT时间
	$now_time = gmtime();
	//统计订单状态
	$order_status_str = " AND oi.order_status='" . OS_FINISH . "' ";
	//最大统计时间
	$max_statistic_days = $GLOBALS['db']->getOne("SELECT MAX(statistic_days) FROM " . $GLOBALS['os']->table('goods') . " WHERE is_hot='0' AND statistic_days>'0' AND hot_number>'0'");
	$max_statistic_time = $now_time - $max_statistic_days * 86400;
	//获得满足条件的所有商品ID
	$goods_ids = $GLOBALS['db']->getCol("SELECT og.goods_id FROM " . $GLOBALS['os']->table('order_goods') . " AS og, " . $GLOBALS['os']->table('order_info') . " AS oi WHERE og.order_id=oi.order_id AND oi.add_time>='{$max_statistic_time}' $order_status_str GROUP BY og.goods_id ");
	foreach($goods_ids as $key => $val) {
		$row = $GLOBALS['db']->getRow("SELECT goods_id,is_hot,statistic_days,hot_number FROM " . $GLOBALS['os']->table('goods') . " WHERE goods_id='{$val}'");
		if ($row['is_hot'] || (!$row['statistic_days'] && !$row['hot_number'])) { continue; }
		//当前统计时间
		$cur_statistic_time = $now_time - $row['statistic_days'] * 86400;
		//热销款需要的数量
		$hot_num = $row['statistic_days'] * $row['hot_number'];
		//已卖出商品的数量
		$sale_num = $GLOBALS['db']->getOne("SELECT COUNT(og.goods_id) FROM " . $GLOBALS['os']->table('order_goods') . " AS og, " . $GLOBALS['os']->table('order_info') . " AS oi WHERE og.order_id=oi.order_id AND oi.add_time>='{$cur_statistic_time}' $order_status_str AND og.goods_id='{$val}' GROUP BY og.goods_id ");
		//判断是否达到热销数量
		if ($sale_num >= $hot_num) {
			$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('goods') . " SET is_hot='1' WHERE goods_id='{$val}' AND is_hot='0'");
			if ($GLOBALS['_CFG']['use_promise_delivery']) {
				$shipping_days = $GLOBALS['db']->getOne("SELECT shipping_days FROM " . $GLOBALS['os']->table('promise_delivery') . " WHERE recommend_type='is_hot'");
				$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('goods') . " SET shipping_days='{$shipping_days}' WHERE goods_id='{$val}'");
			}
		}
	}
	return true;
}

/**
 * 格式化商品图片名称（按目录存储）
 *
 */
function reformat_image_name($type, $goods_id, $source_img, $position='')
{
    $rand_name = gmtime() . sprintf("%03d", mt_rand(1,999));
    $img_ext = substr($source_img, strrpos($source_img, '.'));
    $dir = 'images';
    if (!empty($GLOBALS['filesync']->images_dir))
    {
        $dir = str_replace(SOURCE_DIR.'/', '', $GLOBALS['filesync']->images_dir);
    }
    $sub_dir = date('Ym', gmtime());
    if (!make_dir(SOURCE_PATH.$dir.'/'.$sub_dir))
    {
        return false;
    }
    switch($type)
    {
        case 'goods':
            $img_name = $goods_id . '_G_' . $rand_name;
            break;
        case 'goods_thumb':
            $img_name = $goods_id . '_thumb_G_' . $rand_name;
            break;
        case 'gallery':
            $img_name = $goods_id . '_P_' . $rand_name;
            break;
        case 'gallery_thumb':
            $img_name = $goods_id . '_thumb_P_' . $rand_name;
            break;
        case 'group_pro_gallery':
            $img_name = $goods_id . '_P_' . $rand_name;
            break;
        case 'group_pro_thumb':
            $img_name = $goods_id . '_thumb_P_' . $rand_name;
            break;         
    }

    if (move_image_file(SOURCE_PATH.$source_img, SOURCE_PATH.$dir.'/'.$sub_dir.'/'.$img_name.$img_ext))
    {
        return $dir.'/'.$sub_dir.'/'.$img_name.$img_ext;
    }
    return false;
}

function move_image_file($source, $dest)
{
    if (@copy($source, $dest))
    {
        @unlink($source);
        return true;
    }
    return false;
}

function get_depots(){
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('depot') . " WHERE is_show=1 ORDER BY add_time DESC";
    $depots=$GLOBALS['db']->getAll($sql);
    return $depots;	
}

function get_seats($depot_id=0){
	$where = ' is_show=1 ';
	if($depot_id>0){
		$where .= ' AND depot_id=' . intval($depot_id);
	}
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('seat') . " WHERE $where ORDER BY add_time DESC";
    $seats=$GLOBALS['db']->getAll($sql);
    return $seats;		
}

function insert_depot_seats($arr)
{
	if(!empty($arr['depot_id'])){
		$where = " AND depot_id=" . intval($arr['depot_id']);
	}
	$sql = "SELECT * FROM " . $GLOBALS['os']->table('seat') . " WHERE is_show=1 $where ORDER BY add_time";
	$seats = $GLOBALS['db']->getAllCached($sql);
	$html = '';
    foreach ($seats as $seat){
    	$html .= '<option value="'.$seat['seat_id'].'" '.(($seat['seat_id']==$arr['seat_id']) ? 'selected' : '').'>'.$seat['seat_name'].'</option>';
    }
//    $val = $GLOBALS['smarty']->fetch($html);

    return $html;
}
?>